#pragma once
#include <iostream>
#include <pthread.h>
#include <queue>

template<class T>
class Blockqueue
{
public:
    Blockqueue(int max = 5)
        :_maxqueue(max)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while(_q.size() == 0)
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        T out = _q.front();
        _q.pop();
        pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);

        return out;
    }

    void push(T in)
    {
        pthread_mutex_lock(&_mutex);
        while(_q.size() == _maxqueue)
        {
            pthread_cond_wait(&_p_cond,&_mutex);
        }
        _q.push(in);
        pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);

    }

    ~Blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }
private:
    std::queue<T> _q;
    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
    int _maxqueue;

    int _low_water;
    int _high_water;
};